package com.xsz.oa.realm;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.xsz.oa.helper.PasswordHelper;
import com.xsz.oa.model.entity.sys.User;
import com.xsz.oa.service.ResourceService;
import com.xsz.oa.service.RoleService;
import com.xsz.oa.service.UserService;

/**
 * 自定义realm
 * 
 * @author xsz
 * @date 2015.11.22
 *
 */
@Component
public class UserRealm extends AuthorizingRealm {


	/**
	 * 通过构造函数向AuthicatingRealm中注入CredentialsMatcher,并设置其算法和迭代次数,
	 * 登录的时候会调用其doCredentialsMatch的方法进行密码匹配
	 */
	public UserRealm() {
		HashedCredentialsMatcher matcher = new HashedCredentialsMatcher();
		matcher.setHashAlgorithmName(PasswordHelper.HASH_ALGORITHM);
		matcher.setHashIterations(PasswordHelper.HASH_INTERATIONS);

		setCredentialsMatcher(matcher);
	}

	@Autowired
	private UserService userService;
	@Autowired
	private RoleService roleService;
	@Autowired
	private ResourceService resourceService;

	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		//如果只配置了一个realm 就可以通过这种方式获得用户名
		String username = (String) principals.getPrimaryPrincipal();
		
		//根据用户名查询该用户的角色字符串和权限字符串
		SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
		info.setRoles(roleService.findRoles(username));
		info.setStringPermissions(resourceService.findPermissions(username));
		
		return info;
	}

	/**
	 * 登录时调用,返回认证信息并交给AuthenticatingRealm使用CredentialsMatcher进行密码匹配，
	 * 如果觉得人家的不好可以自定义实现
	 */
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
		String username = (String) token.getPrincipal();
		User user = userService.findByUsername(username);
		if (user == null) {
			throw new UnknownAccountException();// 没找到账号
		}

		if (Boolean.TRUE.equals(user.getLocked())) {
			throw new LockedAccountException(); // 账号锁定
		}

		SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(user.getUsername(), user.getPassword(),
				ByteSource.Util.bytes(user.getCredentialsSalt()), getName());
		return info;
	}

}
